package com.stream;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Collect 是最常用的
 */


public class Stream1 {
    public static void main(String[] args) {
        List<Person> persons = new ArrayList<Person>();
        persons.add(new Person("Tom", 8900, 23, "male", "New York"));
        persons.add(new Person("Jack", 7000, 25, "male", "Washington"));
        persons.add(new Person("Lily", 7800, 21, "female", "Washington"));
        persons.add(new Person("Anni", 8200, 24, "female", "New York"));
        persons.add(new Person("Owen", 9500, 25, "male", "New York"));
        persons.add(new Person("Alisa", 7900, 26, "female", "New York"));

        /**
         * 限制，跳过
         */

        List<Person> collect = persons.stream().filter(person -> person.getSalary() > 7000).limit(2).collect(Collectors.toList());
        System.out.println(collect);

        /**
         * 分组，参考数据库的。也支持多级分组：先按性别分组，再按地区分组。
         *
         * 分区：按条件分为两各部分，比如 员工薪资是否大于 80000
         *
         *
         */

        Map<String, List<Person>> collect1 = persons.stream().collect(Collectors.groupingBy(Person::getArea));



        /**
         * 求总数，求平均工资，求总额，最高
         */
        Long count = persons.stream().filter(person -> person.getSalary() > 8000).
                collect(Collectors.counting());
        System.out.println("大于8000的员工的数量：" + count);
        Double average = persons.stream().collect(Collectors.averagingDouble(Person::getSalary));
        System.out.println("average: " + average);
        Integer sum = persons.stream().collect(Collectors.summingInt(Person::getSalary));

        persons.stream().collect(Collectors.maxBy(new Comparator<Person>() {
            @Override
            public int compare(Person o1, Person o2) {
                return o1.getAge() - o2.getAge();
            }
        }));
        Optional<Person> max = persons.stream().max(Comparator.comparingInt(Person::getSalary));


        /**
         * list 转 map
         */
//        Map<String, Person> personMap = persons.stream().collect(Collectors.toMap(Person::getName, person -> person));
//        for (Map.Entry<String, Person> e : personMap.entrySet()) {
//            System.out.println(e.getKey() + " " + e.getValue());
//
//        }
        //筛选薪资员工大于 8000的员工
//        List<Person> collect = persons.stream().
//                filter(person -> person.getSalary() > 8000).collect(Collectors.toList());
        /**
         *    将所有员工的薪资增加10000
         */
//        List<Person> add10000Salary = persons.stream().map(person -> {
//            person.setSalary(person.getSalary() + 10000);
//            return person;
//        }).collect(Collectors.toList());
//        System.out.println(add10000Salary);

        /**
         * 求最值
         */
//        Person person = persons.stream().max((o1, o2) -> o1.getSalary() - o2.getSalary()).get();
//        System.out.println(person);

    }
}
